<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery" v-perm="'department:list'">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd" v-perm="'department:save'">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="sn" label="编号" width="120" sortable>
      </el-table-column>
      <el-table-column prop="name" label="名称" width="100" sortable>
      </el-table-column>
      <el-table-column prop="dirPath" label="路径" width="120" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" min-width="180" sortable>
        <template scope="scope">
          <span v-if="scope.row.state==0" style="color:red">禁用</span>
          <span v-else style="color:green">启用</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="部门经理" min-width="180" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" min-width="180" sortable>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleSave(scope.$index, scope.row)" v-perm="'department:save'">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)" v-perm="'department:delete'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0" v-perm="'department:patchDel'">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize"
                     :total="totals" :current-page="currentPage" style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增和修改界面-->
    <el-dialog :title=titil :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="编号" prop="sn">
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门经理">
          <el-select v-model="saveForm.manager_id" placeholder="请选择">
            <el-option v-for="item in managers"
                       :label="item.username"
                       :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="saveForm.parent_id"
                       :options="deptTree"
                       :props="{
            checkStrictly: true,
            label: 'name',
            value: 'id'
          }"
                       clearable>
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import {
  getDepartmentListPage,
  removeDepartment,
  batchRemoveDepartment,
  saveDepartment,
  addDepartment
} from '../../api/api';

export default {
  data() {
    return {
      //分页相关的模型数据
      departments: [],     //绑定到表格 - 显示列表数据 - 请求完成之后
      totals: 0,          //总数量 - 计算分页栏 -  请求完成之
      currentPage: 1,     //当前页 - 分页栏默认当前页显示
      pageSize: 5,        //每页显示的条数  - 计算分页栏
      listLoading: false, //表格上的加载框

      keyword: '',

      sels: [],//列表选中列

      //
      titil: '',
      saveFormVisible: false,//编辑界面是否显示
      saveLoading: false,
      saveFormRules: {
        sn: [
          {required: true, message: '请输入编号', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'}
        ]
      },
      //编辑界面数据
      saveForm: {
        id: null,
        sn: '',
        name: '',
        state: 1,
        manager_id: null,
        parent_id: null
      },

      //显示所有的部门经理
      managers: [],

      deptTree: []
    }
  },
  methods: {

    //1.点击某一页触发的方法
    handleCurrentChange(val) {
      this.currentPage = val;//当前页
      this.getDepartments();
    },

    //2.关键字查询
    keywordQuery() {
      this.currentPage = 1;//防止当前页不在第一页的时候 通过关键字查询出现 当前页没有数据的情况
      this.getDepartments();
    },

    //获取用户列表
    getDepartments() {
      let para = {
        currentPage: this.currentPage,	//当前页
        pageSize: this.pageSize,		//每页显示的条数
        keyword: this.keyword
      };
      this.listLoading = true;			//显示加载框/忙等框
      this.$http.post("/department", para).then(res => {
        this.totals = res.data.totals;//给totals赋值 - 计算分页栏
        this.departments = res.data.data;//赋值分页数据 - 显示当前页的分页数据
        this.listLoading = false;//隐藏加载框/忙等框
      }).catch(res => {
        this.$message.error('系统繁忙，请稍后重试!!!');
      });
    },

    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/department/" + row.id).then(res => {
          this.listLoading = false;
          if (res.data.success) {
            this.$message.success("删除成功");

            //删除成功之后对当前页的处理【特殊情况：删除最后一页的最后一条数据】
            var totalPage = Math.ceil(this.totals/this.pageSize); //总页数 = 最后一页
            //如果当前页是最后一页                  并且是最后一条数据                  并且不是第一页
            if(this.currentPage==totalPage && (this.totals-1)%this.pageSize==0 && this.currentPage!=1){
              this.currentPage--;
            }

            this.getDepartments();
          } else {
            this.$message.error("删除失败[500]");
          }
        }).catch(res => {
          this.$message.error("删除失败[400,404]");
        })
      }).catch(() => {
      });
    },

    //
    selsChange: function (sels) {
      this.sels = sels;
    },

    //批量删除
    batchRemove: function () {
      //获取数组中每一个对象的id 并形成新的数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true; //显示加载框
        this.$http.patch("/department", ids).then(res => {
          this.listLoading = false; //隐藏加载框
          if (res.data.success) { //操作成功
            this.currentPage = 1;
            this.getDepartments();
          } else { //操作失败
            this.$message.error("系统繁忙，请稍后重试!!![500]"); //后端500错误走这里
          }
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!![400,404]");
        })
      }).catch(() => {
      });
    },

    //显示编辑界面
    handleSave: function (index, row) {
      this.title = "编辑";
      this.saveFormVisible = true;
      this.saveForm = Object.assign({}, row);
      this.getManagers();
      this.getDeptTree();
    },

    //显示新增界面
    handleAdd: function () {
      this.title = "新增";
      this.saveFormVisible = true;
      this.saveForm = {
        id: null,
        sn: '',
        name: '',
        state: 1,
        manager_id: null,
        parent_id: null
      };
      this.getManagers();
      this.getDeptTree();
    },

    //新增和修改
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.saveForm);
            //对无限极树的情况
            //1.不修改上级部门，没有点级联框:2
            //2.不修改上级部门，点了级联框选择过其他部门:[2]
            //3.去掉上级部门:[]
            //4.[3,9,12]
            //5.null
            var isArr = para.parent_id;
            if(Array.isArray(isArr)){
              if(isArr.length==0){
                para.parent_id=null;
              }else {
                para.parent_id=isArr[isArr.length-1]
              }
            }
            this.$http.put("/department", para).then(res => {
              this.saveFormVisible = false;
              this.saveLoading = false;
              if (res.data.success) {
                this.getDepartments();
              } else {
                this.$message.error("系统繁忙，请稍后重试400，404");
              }
            }).catch(res => {
              this.$message.error("系统繁忙，请稍后重试400，404");
            })
          });
        }
      });
    },

    //获取部门经理 - 所有的员工
    getManagers() {
      this.$http.get("/employee").then(res => {
        this.managers = res.data;
      })
    },

    getDeptTree(){
      this.$http.get("/department/deptTree").then(res => {
        this.deptTree = res.data;
      })
    }
  },

  mounted() {
    this.getDepartments();
  }
}

</script>

<style scoped>

</style>